import React, {useEffect, useRef, useState} from "react";
import {ActionType, ModalForm, PageContainer, ProFormSelect, ProFormText, ProTable} from "@ant-design/pro-components";
import {addOrUpdateAudio, getAllAudios, getAudioCategories, getAudioDetail, uploadFile} from "@/services/audio/audio";
import type {UploadProps} from 'antd';
import {Button, Card, Col, DatePicker, Form, Image, message, Row, Spin, Switch, Tabs, TreeSelect, Upload} from "antd";
import {UploadOutlined} from "@ant-design/icons";
import moment from "moment";
import {AUDIO_SYS_MANAGE, DEPARTMENT_MANAGE, DEPARTMENT_SYS_MANAGE, SALES_MANAGE, SYS_MANAGE} from "@/global.style";
import {currentUser} from "@/services/ant-design-pro/api";
import initialState from "@@/plugin-initialState/@@initialState";
import {useModel} from "@@/exports";

const Audio = () => {
  const { initialState, setInitialState } = useModel('@@initialState');

  const [loading, setLoading] = useState(false);

  const actionRef = useRef<ActionType>();
  const formRef = useRef()
  const [editModal, setEditModal] = useState(false)
  const [isEdit, setIsEdit] = useState(false)
  const [record, setRecord] = useState(null)
  const [quizDetail, setQuizDetail] = useState(null)
  const [qrcode, setQrcode] = useState(null)  //存储二维码地址
  const [url, setUrl] = useState(null)
  const [showQrCodeModal, setShowQrCodeModal] = useState(false)

  const [currentIndex, setCurrentIndex] = useState(0)
  const [size, setSize] = useState(10)

  const [components, setComponents] = useState([])
  const [nextId, setNextId] = useState(0)
  const [file, setFile] = useState(null)
  const [filePath, setFilePath] = useState(null)
  const {RangePicker} = DatePicker;
  const [categoryData, setCategoryData] = useState([])

  const getAudioCategoryList = async () => {
    const res = await getAudioCategories({page: 1, size: 9999})
    if (res.code !== 1) {
      message.error('查询音频类别失败')
      return false
    }
    const categoryData = []
    res.data.records.forEach(category => {
      categoryData.push({
        // title: category.name,
        label: category.name,
        value: category.id
      })
    })
    return categoryData
  }
  useEffect(() => {
    getAudioCategoryList().then(res => {
      setCategoryData(res)
    })
  }, []);

  const shouldShowQRCodeLink = (roles) => {
    const restrictedRoles = [SYS_MANAGE, DEPARTMENT_SYS_MANAGE, AUDIO_SYS_MANAGE];
    return !roles.some(role => restrictedRoles.includes(role));
  }
  const shouldShowAddOrUpdate = (roles) => {
    const restrictedRoles = [DEPARTMENT_SYS_MANAGE,DEPARTMENT_MANAGE, SALES_MANAGE];
    return !roles.some(role => restrictedRoles.includes(role));
  }

  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      hideInSearch: true,
    }, {
      title: '音频名称',
      dataIndex: 'name',
      hideInSearch: true,
    }, {
      title: '音频类别',
      dataIndex: 'categoryName',
      hideInSearch: true,
    }, {
      title: '音频类别',
      dataIndex: 'categoryId',
      hideInTable: true,
      renderFormItem: (_, {type, defaultRender, ...rest}, form) => {
        // 当表单项被渲染时，使用TreeSelect组件
        return <TreeSelect
          {...rest}
          treeData={categoryData}
          placeholder="请选择类别"
          treeDefaultExpandAll
        />;
      },
    }, {
      title: '标号',
      dataIndex: 'tag',
    }, {
      title: '红包奖励',
      dataIndex: 'redPacket',
      hideInSearch: true,
      render: (text, record) => `${record.redPacketStart}-${record.redPacketEnd}`
    }, {
      title: '播放人数',
      dataIndex: 'listenerCount',
      hideInSearch: true,
    }, {
      title: '答题人数',
      dataIndex: 'quizCount',
      hideInSearch: true,
    }, {
      title: '累计发放红包',
      dataIndex: 'totalRedPacket',
      hideInSearch: true,
    }, {
      title: '创建时间',
      dataIndex: 'createdTime',
      valueType: 'dateRange',
      hideInTable: true,
      renderFormItem: (_, {type, defaultRender, ...rest}, form) => {
        // 当表单项被渲染时，使用RangePicker组件
        if (type === 'form') {
          return <RangePicker showTime={{format: 'HH:mm:ss'}} format="YYYY-MM-DD HH:mm:ss" {...rest} />;
        }
        // 使用默认渲染逻辑
        return defaultRender(_);
      },
    }, {
      title: '创建时间',
      dataIndex: 'createdTime',
      hideInSearch: true,
      render: (text) => moment(text).format('YYYY-MM-DD HH:mm:ss')
    }, {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => [
        shouldShowAddOrUpdate(initialState.currentUser.roles) && (<a key="editable" onClick={() => {
          setLoading(true)
          setIsEdit(true)
          setRecord(record)

          console.log('record', record)
          getAudioDetail({
            audioId: record.id
          }).then(res => {
            console.log('audio detail', res)
            if (res.code !== 1) {
              message.error('查询音频详情失败')
              return false
            }
            setQuizDetail(res.data)
            if (res.data.questions.length > 0) {
              const quizs = []
              let id = nextId
              res.data.questions.forEach((question, index) => {
                const newQuiz = <Quiz quizId={id} key={id}/>
                quizs.push(newQuiz)
                id = id + 1
              })
              setNextId(id)
              setComponents(quizs)
            } else {
              console.log('no quiz added')
            }

            setEditModal(true)
          })
        }}>
          编辑
        </a>),
        shouldShowQRCodeLink(initialState.currentUser.roles) && (<a onClick={() => {
          const userInfo = JSON.parse(sessionStorage.getItem('auth'))
          console.log(userInfo)
          const url = 'http://www.tjbaowj.top/audio?audioId=' + record.id + '&wxUid=' + userInfo.uid
          const qrcodeUrl = 'https://api.pwmqr.com/qrcode/create/?url=' + encodeURIComponent(url)
          console.log('qrcode url', qrcodeUrl)
          setQrcode(qrcodeUrl)
          setUrl(url)
          setShowQrCodeModal(true)
        }}>生成二维码</a>)
      ],
    }
  ]
  const props: UploadProps = {
    onChange(info) {
      console.log(info.fileList)
      // if (info.fileList.length > 1) {
      //   info.fileList = [info.fileList[info.fileList.length - 1]]
      // }
      // console.log(info.fileList)
      // setFile(info.file)
      setFile(info.fileList[info.fileList.length - 1]); // 设置最新的一个文件为当前文件
    },
  };

  const {TabPane} = Tabs;

  const Quiz = ({quizId}) => {
    return (
      <Card style={{marginTop: '10px', marginBottom: '10px'}}>
        <Row gutter={24}>
          <Col span={18}>
            <ProFormText key={`q_${quizId}`} name={`question${quizId}`} label="题目"
                         rules={[{required: true, message: '请输入题目'}]}/>
          </Col>
          <Col></Col>
        </Row>
        <Row gutter={24}>
          <Col span={18}>
            <ProFormText key={`op_1_${quizId}`} name={`option1${quizId}`} label="选项1"
                         rules={[{required: true, message: '请输入选项1'}]}/>
          </Col>
          <Col span={6}>
            <Form.Item name={`correct1${quizId}`} valuePropName={'checked'}>
              <Switch
                onChange={(checked) => {
                  console.log('checked', checked)
                  formRef.current?.setFieldsValue({
                    [`correct1${quizId}`]: checked
                  })
                  // 检查至少有一个开关是否被选中
                  const isChecked1 = formRef.current?.getFieldValue(`correct1${quizId}`);
                  const isChecked2 = formRef.current?.getFieldValue(`correct2${quizId}`);
                  if (!isChecked1 && !isChecked2) {
                    // 如果没有开关被选中，则设置表单错误
                    formRef.current?.setFields([
                      {
                        name: `correct1${quizId}`,
                        errors: ['至少选择一个正确答案'],
                      },
                      {
                        name: `correct2${quizId}`,
                        errors: ['至少选择一个正确答案'],
                      },
                    ]);
                  } else {
                    // 如果至少有一个开关被选中，则清除错误信息
                    formRef.current?.setFields([
                      {
                        name: `correct1${quizId}`,
                        errors: [],
                      },
                      {
                        name: `correct2${quizId}`,
                        errors: [],
                      },
                    ]);
                  }
                }}
                checkedChildren="正确答案" unCheckedChildren="正确答案"/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={18}>
            <ProFormText key={`op_2_${quizId}`} name={`option2${quizId}`} label="选项2"
                         rules={[{required: true, message: '请输入选项2'}]}/>
          </Col>
          <Col span={6}>
            <Form.Item name={`correct2${quizId}`} valuePropName={'checked'}>
              <Switch
                onChange={(checked) => {
                  console.log('checked', checked)
                  formRef.current?.setFieldsValue({
                    [`correct2${quizId}`]: checked
                  })
                  // 检查至少有一个开关是否被选中
                  const isChecked1 = formRef.current?.getFieldValue(`correct1${quizId}`);
                  const isChecked2 = formRef.current?.getFieldValue(`correct2${quizId}`);
                  if (!isChecked1 && !isChecked2) {
                    // 如果没有开关被选中，则设置表单错误
                    formRef.current?.setFields([
                      {
                        name: `correct1${quizId}`,
                        errors: ['至少选择一个正确答案'],
                      },
                      {
                        name: `correct2${quizId}`,
                        errors: ['至少选择一个正确答案'],
                      },
                    ]);
                  } else {
                    // 如果至少有一个开关被选中，则清除错误信息
                    formRef.current?.setFields([
                      {
                        name: `correct1${quizId}`,
                        errors: [],
                      },
                      {
                        name: `correct2${quizId}`,
                        errors: [],
                      },
                    ]);
                  }
                }}
                checkedChildren="正确答案" unCheckedChildren="正确答案"/>
            </Form.Item>
          </Col>
        </Row>
      </Card>
    )
  }

  const addQuiz = () => {
    const newQuiz = <Quiz quizId={nextId} key={nextId}/>
    setComponents([...components, newQuiz])
    setNextId(nextId + 1)
  }
  const beforeUpload = (file) => {
    console.log(file.type)
    const isMp3 = file.type === 'audio/mpeg' || file.type === 'audio/x-m4a';
    if (!isMp3) {
      message.error('只能上传 mp3 文件!');
    }
    return false
    // return isMp3 || Upload.LIST_IGNORE;
  };
  return (
    <PageContainer title={'音频列表'}>
      <Spin spinning={loading} tip="加载中...">
        <ProTable
          columns={columns}
          actionRef={actionRef}
          request={async (params, sort, filter) => {
            const reqParams = {
              ...params,
              page: currentIndex,
              size
            }
            if (reqParams.createdTime) {
              reqParams.searchTimeStart = String(params.createdTime).split(',')[0]
              reqParams.searchTimeEnd = String(params.createdTime).split(',')[1]
            }
            const res = await getAllAudios(reqParams);
            return {
              data: res.data.records,
              success: true,
              total: res.data.total
            }
          }}
          pagination={{
            pageSize: size,
            onChange: (page) => setCurrentIndex(page),
          }}
          toolBarRender={() => [
            shouldShowAddOrUpdate(initialState.currentUser.roles) && (<Button
              key="button"
              onClick={() => {
                setEditModal(true)
                setIsEdit(false)
                setRecord(null)
                setFilePath(null)
                setFile(null)
                // actionRef.current?.reload();
              }}
              type="primary"
            >
              新建音频
            </Button>),
          ]}
        />
        <ModalForm
          layout="horizontal" // 设置为水平布局
          labelCol={{span: 4}}
          wrapperCol={{span: 20}}
          formRef={formRef}
          title={isEdit ? '编辑音频' : '新建音频'}
          open={editModal}
          onOpenChange={(open) => {
            console.log('open', open)
            setLoading(false)
            setEditModal(open)
            setFile(null)
            setFilePath(null)

            if (!open) {
              setComponents([])
              setNextId(0)
            }

            console.log('component count', components.length)
            if (isEdit) {
              const questionValues = {}
              quizDetail.questions.forEach((question, index) => {
                questionValues[`question${index}`] = question.questionName
                questionValues[`option1${index}`] = question.answers[0] ? question.answers[0].answerContent : ''
                questionValues[`option2${index}`] = question.answers[1] ? question.answers[1].answerContent : ''
                questionValues[`correct1${index}`] = question.answers[0] ? question.answers[0].isCorrect === 1 : false
                questionValues[`correct2${index}`] = question.answers[1] ? question.answers[1].isCorrect === 1 : false
              })
              const data = {
                ...questionValues,
                category: quizDetail.categoryId,
                tag: quizDetail.tag,
                name: quizDetail.name,
                redPacketStart: quizDetail.redPacketStart,
                redPacketEnd: quizDetail.redPacketEnd,
              }
              console.log('init audio info for edit', data)
              formRef.current?.setFieldsValue(data)

              setFilePath(quizDetail.filePath)
            } else {
              formRef.current?.resetFields()
            }
          }}
          onFinish={async (values) => {
            console.log('edit audio', values)
            console.log('form values', formRef.current.getFieldsValue())

            function validate_answers() {
              let check_validate = true
              for (let i = 0; i < nextId; i++) {
                const isChecked1 = formRef.current?.getFieldValue(`correct1${i}`);
                const isChecked2 = formRef.current?.getFieldValue(`correct2${i}`);
                if (!isChecked1 && !isChecked2) {
                  // 如果没有开关被选中，则设置表单错误
                  formRef.current?.setFields([
                    {
                      name: `correct1${i}`,
                      errors: ['至少选择一个正确答案'],
                    },
                    {
                      name: `correct2${i}`,
                      errors: ['至少选择一个正确答案'],
                    },
                  ]);
                  check_validate = false
                }
              }
              return check_validate;
            }
            //校验每个题目至少有一个正确答案
            let check_validate = validate_answers();
            if (!check_validate) {
              return false
            }
            function generateAudioParams(fp) {
              const params = {
                categoryId: values.category,
                filePath: fp,
                name: values.name,
                redPacketStart: values.redPacketStart,
                redPacketEnd: values.redPacketEnd,
                tag: values.tag,
                questions: [],
              }
              if (isEdit) {
                params.id = record.id
              }
              for (let i = 0; i < nextId; i++) {
                params.questions.push({
                  questionName: values[`question${i}`],
                  answers: [
                    {
                      answerContent: values[`option1${i}`],
                      isCorrect: values[`correct1${i}`] ? 1 : 0,
                    },
                    {
                      answerContent: values[`option2${i}`],
                      isCorrect: values[`correct2${i}`] ? 1 : 0,
                    }
                  ]
                })
              }
              return params;
            }
            const params = generateAudioParams('');
            if (params.questions.length < 4) {
              message.error('题目数量不能少于4个')
              return false
            }

            //先上传文件
            if (file === null && !isEdit) { //是新建
              message.error('请上传音频文件')
              return false
            }
            if (file === null && filePath === null && isEdit) { //是编辑
              message.error('请上传音频文件')
              return false
            }
            console.log('file', file)
            let fp = filePath
            if (file !== null) {
              const formData = new FormData();
              formData.append('file', file.originFileObj);
              const res = await uploadFile(formData)
              if (res.code !== 1) {
                message.error('上传文件失败')
                return false
              }
              console.log('upload file', res.data)
              fp = res.data[0]
            }
            params.filePath = fp

            console.log('edit audio params', params)
            const uploadRes = await addOrUpdateAudio(params)
            if (uploadRes.code === 1) {
              message.success('操作成功')
              actionRef.current?.reload()
              return true
            } else {
              message.error('操作失败')
              return false
            }
          }}
        >
          <Tabs
            tabPosition={'left'}
          >
            <TabPane tab="基础信息" key="1">
              <ProFormSelect
                valuePropName={'value'}
                name="category"
                label="类别"
                options={categoryData}
                placeholder="请选择类别"
                rules={[{required: true, message: '请选择类别'}]}
              />
              <ProFormText name="tag" label="标号"/>
              <ProFormText name="name" label="音频名称"/>
              <ProFormText name="redPacketStart" label="红包奖励开始"/>
              <ProFormText name="redPacketEnd" label="红包奖励结束"/>
              <Form labelCol={{span: 4}}>
                <Form.Item label="音频文件" name="file">
                  <Upload {...props} beforeUpload={beforeUpload}>
                    <Button icon={<UploadOutlined/>}>点击上传</Button>
                  </Upload>
                </Form.Item>
              </Form>
            </TabPane>
            <TabPane tab="答题设置" key="2">
              {/*<Quiz nextId={0} key={0}/>*/}
              {components.map(component => component)}
              <Button onClick={() => {
                const newQuiz = <Quiz quizId={nextId} key={nextId}/>
                setComponents([...components, newQuiz])
                setNextId(nextId + 1)
              }}>添加题目</Button>
            </TabPane>
          </Tabs>
        </ModalForm>
        <ModalForm
          open={showQrCodeModal}
          onOpenChange={(open) => setShowQrCodeModal(open)}
        >
          <div style={{justifyContent: 'center', alignItems: 'center', display: 'flex'}}>
            <div>
              <Row>
                <Col>
                  二维码：
                </Col>
                <Col>
                  <Image src={qrcode} alt={'二维码'}/>
                </Col>
              </Row>
              <Row>
                <Col>
                  链接：
                </Col>
                <Col>
                  <div id={'qrcode_url'}>{url}</div>
                </Col>
                <Col>
                  <a onClick={() => {
                    let ele = document.getElementById("qrcode_url");
                    navigator.clipboard.writeText(ele.innerText);
                    alert("已复制好，可贴粘。");
                  }} style={{marginLeft: '20px'}}>复制</a>
                </Col>
              </Row>
            </div>
          </div>
        </ModalForm>
      </Spin>
    </PageContainer>
  )
}

export default Audio;
